
var guiguVue = new Vue({
  el: '#outLinePage',
  data() {
    return {
      openId: '',
      // 分享拼团页面
      courseItems: {
        '10001': 'Wonders--启蒙班',
        '10002': 'Wonders--基础班',
        '10003': 'Wonders--进阶班'
      },
      classInfo:{},
      groupOrderId: '',
      name: '',
      mobile: '',
      nextClassSchedule:{},
      alertBox: false,
      orderId: '' // 是否是老用户（用来判断绑定）
    }
  },
  methods: {
    getUrlData(dataName) {
      function getUrlVars() {
        var vars = {}, hash;
        var href = window.location.href.split('#')[0];
        var hashes = href.slice(href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
          hash = hashes[i].split('=');
          vars[hash[0]] = hash[1] ? hash[1] : '';
        }
        return vars;
      }
      var params = getUrlVars();

      for (var key in params) {
        if (key == dataName) {
          return params[key];
        }
      };
      return '';
    },
    isWeiXin() {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
      } else {
        return false;
      }
    },
    handleSubmit() {
      
			if (this.groupOrderId){
        // 线下报名或绑定老用户
        this.orderId ? this.handleBinding() : this.addGroup();									
			} 
    
    },
    // 线下报名
    addGroup(){
      var self = this;
      if (self.name == '') {
        guigu.showModal({
          content: '请填写学员英文名',
          showCancel: false
        });
      } else if (!/^1\d{10}$/.test(self.mobile)) {
        guigu.showModal({
          content: '请填写正确的联系电话',
          showCancel: false
        });
      } else {
          this.addGroupToBase();
      }	
    },
    //绑定老用户
    async handleBinding() {
      if (!this.openId) {
        guigu.showModal({
          content: '没有unionId',
          showCancel: false
        });
        return false;
      }
      if (this.name === '') {
        guigu.showModal({
          content: '请填写学员英文名',
          showCancel: false
        });
      } else {

        var self = this;
        guigu.showLoading({
          title: '数据加载中',
          mask: true
        });
        $.ajax({
          url: 'https://api.svenglish.cn/api/wechat/old-user-unionid',
          type: 'POST',
          contentType: 'application/json',
          data: JSON.stringify({
            unionId: this.openId,
            childName: this.name,
            orderId: this.orderId,
            groupOrderId: this.groupOrderId
          }),
          success:function(data){
            //成功
            guigu.hideLoading();
            if (data.code===1) {
              self.alertBox = true;
            }else{
              //关闭loading
              guigu.showModal({
                content: data.msg,
                showCancel: false
              });
            }
          },
          fail(res) {
            //关闭loading
            guigu.hideLoading();
            guigu.showModal({
              content: '请求失败，请重试！',
              showCancel: false
            });
          }
        });
      }
    },
    // 获取课程信息
    async getClassInfo() {
      this.groupOrderId = this.getUrlData('groupOrderId');
      if (!this.groupOrderId) {
        return false;
      }

      const res = await axios.get('https://api.svenglish.cn/api/order/class-info?groupOrderId=' + this.groupOrderId);
      let resData = res.data;
      if (resData.code !== 1) {
        console.log( 'msg:' + resData.msg);
        return;
      }
      
      this.classInfo = resData.data;

    },
    async pretend(orderId,groupOrderId){
      var self = this;
      $.ajax({
				url: 'https://api.svenglish.cn/api/payment/pretend',
				type: 'POST',
				contentType: 'application/json',
				data: JSON.stringify({
					objectType: "COURSE",
					objectId: orderId
				}),
				success:function(data){
          //成功
          guigu.hideLoading();
					if (data.code===1) {
						self.alertBox = true;
					}else{
						//关闭loading
						guigu.showModal({
							content: data.msg,
							showCancel: false
						});
					}
				},
				fail(res) {
					//关闭loading
					guigu.hideLoading();
					guigu.showModal({
						content: '请求失败，请重试！',
						showCancel: false
					});
				}
			}); 
    },
    async addGroupToBase() {
      let putData = {
				groupOrderId: this.groupOrderId,
        openId: this.openId,
        courseId:this.classInfo.courseId,
				contactName: this.name,
        contactPhone: this.mobile,
        amount:0,
        originator: 0        
      };

      //检测并开启loading
			guigu.showLoading({
				title: '数据加载中',
				mask: true
			})
      const res = await axios.put('https://api.svenglish.cn/api/order/course',putData);
      if (res.data.code !==1 ) {
         //关闭loading
         guigu.hideLoading();
         guigu.showModal({
           content: res.data.msg,
           showCancel: false
         });
      }else {
        guigu.hideLoading();
        this.alertBox = true;
      //   this.pretend(res.data.data.orderId,putData.groupOrderId);
       }
    }
  },
  mounted() {
    var wxUserInfo = localStorage.getItem('wxUserInfo');
    this.orderId = this.getUrlData('orderId');
		if(wxUserInfo){
			var wxUserInfo = JSON.parse(wxUserInfo);
      this.openId = wxUserInfo.unionId;
      if (!this.openId && this.isWeiXin()) {
        location.href = 'login.html?url='+encodeURIComponent(location.href.split('#')[0]);
      }
		}else if(this.isWeiXin() && !wxUserInfo){
			location.href = 'login.html?url='+encodeURIComponent(location.href.split('#')[0]);
		}
    this.getClassInfo();
    
    
    var urlPath = window.location.href.split('?')[0].replace(/(.+\/).*$/g, '$1'); //URL根目录
		guigu.share({
			title: '硅谷少儿英语-课程信息登记', // 分享标题
			desc: '完成登记后，您可通过”硅谷少儿英语学习助手”微信小程序对您的课程进行查阅和管理', // 分享描述
			link: window.location.href, //分享地址
			imgUrl: urlPath+'images/logo_square.png',  //分享的图片地址，需绝对路径
			success: function () { 
				
			},
			cancel: function () { 
				
			}
    });
    
  }
  
});